package com.stockz.equity.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.stereotype.Repository;

import com.stockz.equity.model.Scrip;

@Repository
public class ScripDaoImpl implements ScripDao {

	@Autowired private JpaTemplate jpaTemplate;
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Scrip> getAllScripList() {
		return jpaTemplate.findByNamedQuery(Scrip.GetAllScripQuery);
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Scrip> getAllScripList(Date date){
		return jpaTemplate.findByNamedQuery(Scrip.GetAllScripForDateQuery, date);
	}
	
	@Override
	public void persist(final Scrip scrip) {
		jpaTemplate.execute(new JpaCallback<Object>(){
			@Override
			public Object doInJpa(EntityManager em)
					throws PersistenceException {
				EntityTransaction transaction = em.getTransaction();
				transaction.begin();
				em.persist(scrip);
				transaction.commit();
				return null;
			}
			
		});
	}
	
	@Override
	public Scrip merge(final Scrip scrip) {
		return jpaTemplate.execute(new JpaCallback<Scrip>(){
			@Override
			public Scrip doInJpa(EntityManager em)
					throws PersistenceException {
				EntityTransaction transaction = em.getTransaction();
				transaction.begin();
				Scrip managed = em.merge(scrip);
				transaction.commit();
				return managed;
			}
			
		});
	}
	
}
